package com.jiumi.framework.security.handle;


import com.jiumi.common.constant.HttpStatus;
import com.jiumi.common.core.domain.AjaxResult;
import com.jiumi.common.utils.ServletUtils;
import com.jiumi.common.utils.StringUtils;
import com.alibaba.fastjson2.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;

/**
 * 认证失败处理类 返回未授权
 *
 * @author jiumi
 */
@Component("authenticationEntryPointApi")
public class AuthenticationEntryPointApiImpl implements AuthenticationEntryPoint, Serializable
{
    private static final Logger logger = LoggerFactory.getLogger(AuthenticationEntryPointApiImpl.class);

    private static final long serialVersionUID = -8970718410437077609L;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
    {
        logger.error("未登录",e.toString());
        int code = HttpStatus.UNAUTHORIZED;
        String msg = StringUtils.format("未登录", request.getRequestURI());
        ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(code, msg)));
    }
}
